package com.wits.qso.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.CList;
import com.wits.qso.entity.Course;
import com.wits.qso.service.CListService;
import com.wits.qso.service.CourseService;

/**
 * @author Ethan Lee
 */
@Controller
@RequestMapping(value = "qso/clist")
public class CListController extends BaseController
{
	protected static final Logger logger = LoggerFactory.getLogger( CListController.class );

	@Autowired
	private CListService cListService = null;
	@Autowired
	private CourseService courseService = null;

	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/clist/list";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public String list(Model model, @ModelAttribute("page") PageParam page, HttpServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith( request, "search_" );
		Page<CList> listPage = cListService.findPage( CList.class, searchParams, page );
		model.addAttribute( "searchParams", Servlets.encodeParameterStringWithPrefix( searchParams, "search_" ) );
		return PageUtil.toAjaxPageResult( listPage.getTotalElements(), listPage.getContent() );
	}

	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType, @RequestParam String id) {
		boolean display = true;
		if (ViewType.Add.getView().equals( viewType )) {
			model.addAttribute( WebConstants.COMMAND, new CList() );
		} else {
			CList cList = cListService.getOne( id );
			
			if (ViewType.Modify.getView().equals( viewType ) && null == cList.getFatherId()) { 
				display = false;
			}
			
			model.addAttribute( WebConstants.COMMAND, cList );
		}
		
		model.addAttribute( "display", display );
		model.addAttribute( "hasRootNode", cListService.hasRootNode() );
		model.addAttribute( "cLists", cListService.findAll() );
		model.addAttribute( "viewType", viewType );

		return "qso/clist/form";
	}

	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object save(Model model, @ModelAttribute("command") @Valid CList command, @RequestParam String viewType,
	        @RequestParam(value = "parentId") String parentId, BindingResult result) {
		if (result.hasErrors()) {
			model.addAttribute( WebConstants.COMMAND, command );
			return toView( model, viewType, command.getId() );
		}
		if (ViewType.Add.getView().equals( viewType )) {
			command.setDateCre( new Date() );
			command.setUserCre( getCurrentUserId() );
		} else {
			command.setDateUpd( new Date() );
			command.setUserUpd( getCurrentUserId() );
		}
		try {
			if (StringUtils.isNotBlank( parentId )) {
				command.setFatherId( cListService.getOne( parentId ) );
			}
			cListService.save( command );
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "save.failed" ), e );
		}
	}

	@RequestMapping(value = "/course")
	public String addCourse(Model model, @RequestParam String id) {
		model.addAttribute( "cListId", id );
		List<Course> cListCourses = courseService.findByLst( cListService.getOne( id ) );
		List<Course> unknowCourses = courseService.findUnKnowLst();
		cListCourses.addAll( unknowCourses );

		model.addAttribute( "courses", cListCourses );

		return "qso/clist/course";
	}

	@RequestMapping(value = "/course/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object saveCourse(Model model, @RequestParam(value = "cListId") String cListId, @RequestParam(value = "courseIds") String courseIds) {
		try {
			logger.info( "{}", courseService.resetListId( cListId ) );
			if (StringUtils.isNotBlank( courseIds )) {
				String[] courses = courseIds.split( "," );
				CList cList = cListService.getOne( cListId );

				for (String courseId : courses) {
					Course course = courseService.getOne( courseId );
					course.setListId( cList );
					courseService.save( course );
				}
			}
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "save.failed" ) );
		}
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;

		for (String id : Arrays.asList( StringUtil.split( ids, "," ) )) {
			try {
				cListService.delete( id );
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}

		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError( "有些被引用的节点無法刪除" );
			} else {
				return ajaxDoneSuccess( this.getText( "delete.success" ) );
			}
		} else {
			return ajaxDoneError( "該节点已經被引用，無法刪除" );
		}
	}
}
